﻿var request;
var balance;

//validate number
function validate_cv(text){
	var regexp = new RegExp("-?\\d+\.?\\d*");
	return regexp.test(text);
}

//comparison float
function is_less(val1, val2){
	var value1 = parseFloat(val1);
	var value2 = parseFloat(val2);
	return value1 < value2;
} 

// Saves options to localStorage.
function save_options(){

  //save login
  var login = document.getElementById("login");
  var enteredLogin = login.value;
  localStorage["login"] = enteredLogin;

  // save password
  var password = document.getElementById("password");
  var enteredPassword = password.value;
  localStorage["password"] = enteredPassword;
  
  //save active listeners
  localStorage["listeners"] = JSON.stringify(get_listeners());
}

// Restores select box state to saved value from localStorage.
function restore_options() {
  //restore login
  var enteredLogin = localStorage["login"];
  if (!enteredLogin) {
    return;
  }
  var login = document.getElementById("login");
  login.value = enteredLogin;
  
  //restore password
  var enteredPassword = localStorage["password"];
  if (!enteredPassword) {
    return;
  }
  var password = document.getElementById("password");
  password.value = enteredPassword;
  
  //restore listeners table
  var listeners = JSON.parse(localStorage["listeners"]);
  if (!listeners) {
    return;
  }
  
  for (i=0; i<listeners.length; i++)
  {
		add_listener_to_table(listeners[i].id, listeners[i].critical_value, listeners[i].is_active);
  }
}

function add_listener(){
	var next_listener_id;
	var listeners_number = $("#listeners tr").length;
	if (listeners_number === 0){
		next_listener_id = 1;
	}else{
		next_listener_id = parseInt($("#listeners tr:last-child td")[0].innerHTML) + 1;
	}
	
	var cv = $("#new_listener_cv").val();
	if (!validate_cv(cv)){
		show_temporary_notification('Incorrect balance string, be sure you entered correct balance', 2000);
		return;
	};
	add_listener_to_table(next_listener_id, cv, false);
}

function add_listener_to_table(id, listener_cv, active){
	var table = $("#listeners")[0];
	var row = table.insertRow(table.rows.length);
	var id_cell = row.insertCell(0);
	id_cell.innerHTML=id;
	id_cell.setAttribute("class","first_cell");
	id_cell.setAttribute("align", "center");
	var critical_value_cell = row.insertCell(1);
	critical_value_cell.innerHTML = listener_cv;
	critical_value_cell.setAttribute("align", "center");
	var active_cell = row.insertCell(2);
	active_cell.setAttribute("align", "center");
	if (active) active_cell.innerHTML = '<input type=\"checkbox\" checked/>';
	else active_cell.innerHTML = '<input type=\"checkbox\"/>';
	var delete_cell = row.insertCell(3);
	delete_cell.setAttribute("align","center");
	delete_cell.innerHTML = "<div class=\"btn_delete\" onClick=\"remove_listener(this)\"/>";
	delete_cell.setAttribute("class","last_cell");
}

function remove_listener(button){
	var rowIndex = button.parentNode.parentNode.rowIndex;
	var table = $("#listeners")[0];
	table.deleteRow(rowIndex);
}

//get balance
function get_balance(is_button){
  new Ajax.Request("http://cabinet.telecom.mipt.ru",
  {
    method:'get',
	onFailure: function(){ alert('Somethind went wrong...') }
  });
  new Ajax.Request('http://cabinet.telecom.mipt.ru',
  {
    method:'post',
	parameters: {login: localStorage["login"], password: localStorage["password"]},
    onSuccess: function(transport){
      var response = transport.responseText || "no response text";
      var regexp = new RegExp("(-?\\d+\.\\d{2}).*руб");
	  balance = regexp.exec(response)[1];
	  var balanceLabel = document.getElementById("balance");
	  if (balance)
			localStorage["balance"] = balance;
	  else 
			localStorage["balance"] = "Please, specify your login information";
			
	  if (is_button){
		 $("#balance").text(balance);
		 if (window.webkitNotifications.checkPermission() == 0) {
				show_temporary_notification('Balance was updated: ' + balance, 10000);
			}
	  }
    },
    onFailure: function(){ alert('Something went wrong...') }
  });
}

//get listeners from table
function get_listeners(){
	var listeners = new Array();
	$("#listeners tr").each(function(i){
		var id = this.cells[0].innerHTML;
		var cv = this.cells[1].innerHTML;
		var active = this.cells[2].childNodes[0].checked;
		listeners.push(new balanceListener(id,cv,active));
	});
	return listeners;
}

//get balance to popup page from localStorage
function get_balance_from_memory(){
	var account = localStorage["balance"];
	if (account != 'undefined') return account;
	get_balance(false);
	if (account != 'undefined') return 'Please, insert your account information';
	return account;
}


function check_balance(){
    listeners = JSON.parse(localStorage["listeners"]);
	get_balance(false);
	var min_cv = Number.MAX_VALUE;
	var min_cv_listener_id = -1;
	for (i = 0; i < listeners.length; i++){
		if (listeners[i].is_active && listeners[i].critical_value < min_cv && is_less(balance, listeners[i].critical_value)){
			min_cv = listeners[i].critical_value;
			min_cv_listener_id = listeners[i].id;
		}
	}
	if (min_cv_listener_id !== -1){
			check_listener(min_cv_listener_id, min_cv, balance);
	}
}

//refresh balance
function refresh_balance(){
   new PeriodicalExecuter(check_balance, 600);
}

//close current tab
function close_current_tab(){
	chrome.tabs.getCurrent(function (tab)
	{
		chrome.tabs.remove(tab.id);
	});
}

//open options page in new tab
function option_tab(){
	chrome.tabs.create({"url":"html/options.html", "selected":true});
}

function check_listener(id, cv, balance){
	if (window.webkitNotifications.checkPermission() == 0) {
		  var notification = window.webkitNotifications.createHTMLNotification(
		  'notification.html?cv=' + cv + '&balance=' + balance);
		  setTimeout(function(){
			  notification.cancel();
			}, 10000);
		  notification.show();
		}
}

function show_temporary_notification(message, timeout){
	var notification = window.webkitNotifications.createNotification(
						'../img/icon.png',
						'BalanceNotificator',
						message);
		  setTimeout(function(){
			  notification.cancel();
			}, timeout);
		  notification.show();
}

function get_listener_by_id(id){
	var listeners = JSON.parse(localStorage["listeners"]);
	for (i = 0; i < listeners.length; i++)
	{
		if (listeners[i].id == id) return listeners[i];
	}
	return null;
}
  